<template>
  <el-dialog
    :title="dialogTitle"
    :visible="dialogFormVisible"
    @close="dialogClose"
  >
    <el-form :model="stuForm" :rules="stuRules" ref="addStuRuleForm">
      <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload
          class="uploadAvatar"
          ref="uploadAvatar"
          :limit="limit"
          :multiple="false"
          list-type="picture-card"
          name="headimgurl"
          action="https://chst.vip/students/uploadStuAvatar"
          :show-file-list="true"
          :on-success="uploadSuccess"
          :on-remove="removeAvatar"
          :file-list="headimgList"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
        <el-input v-model="stuForm.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="项目地址"
        :label-width="formLabelWidth"
        prop="productUrl"
      >
        <el-input v-model="stuForm.productUrl" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="班级" :label-width="formLabelWidth" prop="class">
        <el-input v-model="stuForm.class" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
        <el-input v-model="stuForm.age" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="城市" :label-width="formLabelWidth" prop="city">
        <el-input v-model="stuForm.city" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="学历" :label-width="formLabelWidth" prop="degree">
        <el-input v-model="stuForm.degree" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="经历"
        :label-width="formLabelWidth"
        prop="description"
      >
        <el-input v-model="stuForm.description" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="HIDE_DIALOG">取 消</el-button>
      <el-button type="primary" @click="confirmClick('addStuRuleForm')"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex";
// 引入发起请求的api
import * as api from "@/api/users";
export default {
  data() {
    return {
      headimgList: [], //回显的头像
      oldFrom:{}, // 储存stuForm的初始值，便于后续清空dialog内容
      limit:1, // 上传文件的数量
      stuForm: {
        name: "",
        productUrl: "",
        class: "",
        age: "",
        city: "",
        degree: "",
        headimgurl: "",
        description: "",
      },
      formLabelWidth: "100px",
      stuRules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        productUrl: [
          { required: true, message: "请输入项目地址", trigger: "blur" },
        ],
        class: [{ required: true, message: "请输入班级", trigger: "blur" }],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        city: [{ required: true, message: "请输入城市", trigger: "blur" }],
        degree: [{ required: true, message: "请输入学历", trigger: "blur" }],
        description: [
          { required: true, message: "请描述经历", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    // 储存stuForm的初始值，便于后续清空dialog内容
    this.oldFrom = {...this.stuForm}
  },
  computed: {
    ...mapState(["dialogFormVisible", "dialogTitle", "currentRow"]),
  },
  methods: {
    ...mapMutations(["HIDE_DIALOG", "CHANGE_DIALOG_TITLE"]),
    ...mapActions(["GET_STULIST"]),

    // dialogo关闭的时候触发的回调
    dialogClose(){
      // 关闭dialog
      this.HIDE_DIALOG();
      // 情况输入框中的值
      this.stuForm = this.oldFrom
      // 清空回显头像的数据，不让有动画显示
      this.headimgList = []
      // 关闭dialog的时候让limit,成为1个
      this.limit = 1
    },

    // 上传成功的钩子
    uploadSuccess(res) {
      console.log(res);
      // 把返回的图片地址，添加给stuForm,传给服务器，保存到数据库
      if (res.state) {
        this.stuForm.headimgurl = res.headimgurl;
          if(this.dialogTitle === "编辑学员信息"){
            setTimeout(() => {
              //把headimgList列表内容设为当前项
              this.headimgList = [{url:res.headimgurl}]
            },500)
          }
      } else {
        this.$message.error("头像上传失败");
      }
    },

    // 上传失败的钩子
    removeAvatar(s) {},

    // 确定按钮触发的
    confirmClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 关闭dialog
          this.HIDE_DIALOG();
          // 表单验证成功
          // 发送请求
          // 判断'dialogTitle'
          if (this.dialogTitle === "增加学员信息") {
            // 发起增加的请求
            // console.log(this.stuForm);
            api.addStuApi(this.stuForm).then((res) => {
              console.log(res);
              if (res.data.state) {
                // 增加成功
                // 重新发起请求，跟新表格内容
                this.GET_STULIST();
                this.$message.success("增加成功")
              } else {
                // 增加失败
                this.$message.error("提交失败");
              }
            });
          } else {
            // 发起编辑的请求
            api.updataStuApi(this.stuForm)
            .then((res) => {
              console.log(res);
              // 判断跟新状态
              if(res.data.state){
                // 修改成功，跟新视图
                this.GET_STULIST();
                this.$message.success("修改成功")
              }else{
                // 更新失败，提示   (比如你在更新列表时，这条数据被人删除)
                this.$message.error("更新失败,没有做任何修改,或者数据不存在")
                // 更新页面列表
                this.GET_STULIST()
              }
            })
          }
        } else {
          this.$message.error("将内容填写完整");
          // 表单验证不成功
        }
      });
    },
  },
  watch: {
    currentRow(newVal) {  // 监听传入的currentRow的数据变化
      // console.log(newVal);
      // 数据回显，从vuex中获取到当前回显的数据
      console.log(this.currentRow);
      // console.log(this.stuForm);
      this.stuForm = this.currentRow; // 回显变化的数据
      // 回显头像
      this.headimgList = [{url:this.currentRow.headimgurl}]
      // 编辑的时候让Limit变成2个
      this.limit = 2
    },
  },
};
</script>

<style>
.uploadAvatar {
  text-align: left;
}
.el-upload-list__item.is-success,
.el-upload--picture-card {
  width: 100px !important;
  height: 100px !important;
  line-height: 100px !important;
}
.el-dialog__header {
  padding: 0 !important;
  line-height: 60px;
}
</style>
